package com.xinxin.base.util;

import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;

/**
 * 验证码工具类，重写 {@link com.wf.captcha.utils.CaptchaUtil}
 * 因为它没有提供修改验证码类型方法
 *
 * @author ys
 * @date 2020/5/15
 */
public class CaptchaUtil {

    // gif 类型验证码
    public static final int GIF_TYPE = 0;
    // png 类型验证码
    public static final int PNG_TYPE = 1;

    // 验证码默认位数
    private static final int DEFAULT_LEN = 4;
    // 验证码图片默认宽度
    private static final int DEFAULT_WIDTH = 130;
    // 验证码图片默认高度
    private static final int DEFAULT_HEIGHT = 48;

    public static Captcha gif() {
        return gif(DEFAULT_LEN);
    }

    public static Captcha gif(int len) {
        return gif(len, DEFAULT_WIDTH, DEFAULT_HEIGHT, null);
    }

    public static Captcha gif(int len, Font font) {
        return gif(len, DEFAULT_WIDTH, DEFAULT_HEIGHT, null, font);
    }

    public static Captcha gif(int len, int width, int height, Integer vType) {
        return gif(len, width, height, vType, null);
    }

    public static Captcha gif(int len, int width, int height, Integer vType, Font font) {
        return captcha(len, width, height, vType, font, GIF_TYPE);
    }

    public static Captcha png() {
        return png(DEFAULT_LEN);
    }

    public static Captcha png(int len) {
        return png(len, DEFAULT_WIDTH, DEFAULT_HEIGHT, null);
    }

    public static Captcha png(int len, Font font) {
        return png(len, DEFAULT_WIDTH, DEFAULT_HEIGHT, null, font);
    }

    public static Captcha png(int len, int width, int height, Integer vType) {
        return png(len, width, height, vType, null);
    }

    public static Captcha png(int len, int width, int height, Integer vType, Font font) {
        return captcha(len, width, height, vType, font, PNG_TYPE);
    }

    private static Captcha captcha(int len, int width, int height, Integer vType, Font font, int cType) {
        Captcha captcha = GIF_TYPE == cType ? new GifCaptcha(width, height, len) : new SpecCaptcha(width, height, len);

        if (vType != null) {
            captcha.setCharType(vType);
        }

        if (font != null) {
            captcha.setFont(font);
        }

        return captcha;
    }

    public static void setHeader(int cType, HttpServletResponse response) {
        String contentType = GIF_TYPE == cType ? MediaType.IMAGE_GIF_VALUE : MediaType.IMAGE_PNG_VALUE;
        response.setContentType(contentType);
        response.setHeader(HttpHeaders.PRAGMA, "No-cache");
        response.setHeader(HttpHeaders.CACHE_CONTROL, "No-cache");
        response.setDateHeader(HttpHeaders.EXPIRES, 0L);
    }
}
